'use strict';

const Controller = require('egg').Controller;
const moment = require('moment');
const md5 = require('md5');

class AdminController extends Controller {
  // 查询全部admin用户
  async index() {
    const { ctx } = this;
    const users = await ctx.service.admin.findAll();
    for (const user of users) {
      if (user.last_login_time !== 0) {
        user.last_login_time = moment.unix(user.last_login_time).format('YYYY-MM-DD HH:mm:ss');
      } else {
        user.last_login_time = '还没有登录过';
      }
      user.password = '';
    }
    ctx.body = { code: 0, data: users };
    ctx.status = 200;
  }
  // 添加管理员
  async getAdminDetail() {
    const { ctx } = this;
    const id = ctx.query.id;
    const info = await ctx.service.admin.getAdminDetail(id);
    ctx.body = {
      code: 0,
      data: {
        id: info.id,
        username: info.username,
      },

    };
    ctx.status = 200;
  }
  // 新增用户
  async addAdmin() {
    const { ctx } = this;
    // console.log('this.body:', this.body);
    // console.log('this.ctx.body:', ctx.request.body);
    let { username, password } = ctx.request.body;

    password = password.replace(/(^\s*)|(\s*$)/g, '');
    let result = {
      code: -1,
      msg: '请求成功',
    };
    let status = 200;
    if (password.length !== 0) {
      password = md5(password + this.config.passwordSalt);
    } else {
      result = {
        code: -1,
        msg: '密码不能为空',
      };
      status = 403;
    }
    const data = {
      username,
      password,
    };
    const res = await ctx.service.admin.addAdmin(data);
    if (res.code === 0) {
      result = {
        ...res,
      };
      status = 200;
    } else {
      result = {
        code: -1,
        msg: '服务请求错误',
      };
      status = 500;
    }

    ctx.body = result;
    ctx.status = status;
  }
  // 删除一个管理员
  async deleteAdmin() {
    const { ctx } = this;
    const id = ctx.request.body.id;
    const result = {
      code: 0,
      msg: '删除成功',
    };
    const status = 200;
    if (id !== null || id !== undefined) {
      const res = await ctx.service.admin.deleteAdmin(id);
      // console.log('control res:', res);
      if (res.code !== 0) {
        result.code = res.code;
        result.msg = '删除失败';
      }
    } else {
      result.code = -1;
      result.msg = 'id不存在';
    }
    ctx.body = result;
    ctx.status = status;
  }

  // 更新管理员
  async updateAdmin() {
    const { ctx } = this;
    const result = {
      code: 0,
      msg: '更新成功',
    };
    const status = 200;
    const data = ctx.request.body;
    let password = data.password;
    if (password) {
      password = data.password.replace(/(^\s*)|(\s*$)/g, '');
      if (password.length !== 0) {
        password = md5(password + this.config.passwordSalt);
        data.password = password;
      }
    }


    const res = await ctx.service.admin.updateAdmin(data);
    if (res.code === -2) {
      result.code = -1;
      result.msg = '用户名重复了';
    } else if (res.code !== 0) {
      result.code = -1;
      result.msg = '更新失败';
    }
    ctx.body = result;
    ctx.status = status;
  }

  // 管理端登录
  async login() {
    const { ctx } = this;
    try {
      ctx.validate({
        username: { type: 'string', required: true },
        password: { type: 'string', required: true },
      }, ctx.request.body);

      const { username, password } = ctx.request.body;
      // 根据用户名去查用户信息
      const user = await this.app.mysql.get('admin', { username });
      // console.log('user:', user);
      if (!user) {
        ctx.body = {
          code: -1,
          msg: '用户名不存在',
        };
        ctx.status = 200;
      } else {
        if (md5(password + this.config.passwordSalt) === user.password) {
          // 生成token
          const token = this.app.jwt.sign(
            {
              username: user.username,
            },
            this.config.jwt.secret
          );
          ctx.set({
            token,
          });
          // 登录成功
          ctx.body = {
            code: 0,
            msg: '登录成功',
            data: {
              id: user.id,
              token,
            },
          };
        } else {
          ctx.body = {
            code: -1,
            msg: '密码错误',
          };
        }
      }
    } catch (err) {
      ctx.logger.error(err.errors);
      ctx.body = {
        code: -1,
        msg: '用户名和密码不能为空',
      };
    }
  }
}

module.exports = AdminController;
